<script setup>
import { reactive, ref } from 'vue'
import pageContainer from '../../components/pageContainer.vue'
import { useUserStore } from '@/stores'
import { userUpdateInfoService } from '@/api/user'

const {
  user: { nickname, email, username, id },
  getUser
} = useUserStore()
// 表单数据
const formData = reactive({
  username, // 示例值，禁用状态不可编辑
  nickname,
  email,
  id
})

// 表单引用
const formRef = ref()

// 校验规则
const rules = {
  nickname: [
    { required: true, message: '昵称不能为空', trigger: 'blur' },
    { min: 2, max: 10, message: '昵称长度需为2-10个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: '请输入正确的邮箱格式',
      trigger: 'blur'
    }
  ]
}

// 提交处理函数
const handleSubmit = async () => {
  //表单校验
  await formRef.value.validate()
  const res = await userUpdateInfoService(formData)
  console.log(res)
  getUser()
  ElMessage.success('提交成功!')
}
</script>

<template>
  <pageContainer title="基本资料">
    <el-row>
      <el-col :span="12">
        <el-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="100px"
          @submit.prevent="handleSubmit"
        >
          <!-- 登录名称 -->
          <el-form-item label="登录名称">
            <el-input v-model="formData.username" disabled />
          </el-form-item>

          <!-- 用户昵称 -->
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="formData.nickname" />
          </el-form-item>

          <!-- 用户邮箱 -->
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="formData.email" />
          </el-form-item>

          <!-- 提交按钮 -->
          <el-form-item>
            <el-button type="primary" native-type="submit">提交修改</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </pageContainer>
</template>

<style scoped>
/* 可选样式 */
.el-input {
  width: 300px;
}
</style>
